package com.timepies.activity;

import static com.timepies.database.Service.getInstance;

import java.util.Calendar;

import android.app.Activity;
import android.app.DatePickerDialog;
import android.app.DatePickerDialog.OnDateSetListener;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnFocusChangeListener;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.Toast;

import com.timepies.R;
import com.timepies.database.Service;
import com.timepies.domain.Intervallo;
import com.timepies.domain.Timepie;

public class ModificaPieActivity extends Activity {

	private Timepie pie = null;
	private Class<?> caller = null;
	private Service service = null;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_pie_modifica);

		this.pie = (Timepie) getIntent().getSerializableExtra("pieObj");
		this.caller = (Class<?>) getIntent().getSerializableExtra("caller");
		this.service = getInstance(this);

		EditText campoData = (EditText) findViewById(R.id.data);

		if (pie != null)
			setupModifica(campoData);
		else
			setupCrea(campoData);

		Log.d(toString(), "onCreate");
	}

	// MODIFICA
	public void setupModifica(final EditText campoData) {
		EditText testo = (EditText) findViewById(R.id.testo);
		EditText oggetto = (EditText) findViewById(R.id.oggetto);
		EditText date = (EditText) findViewById(R.id.data);
		testo.setText(pie.getTesto());
		oggetto.setText(pie.getOggetto());
		date.setText(pie.getData());
		campoData.setTextColor(Color.parseColor("gray"));
	}

	// CREAZIONE
	public void setupCrea(final EditText campoData) {
		((Button) findViewById(R.id.crea_button)).setVisibility(View.VISIBLE);
		((Button) findViewById(R.id.modifica_button)).setVisibility(View.GONE);

		campoData.setOnFocusChangeListener(new OnFocusChangeListener() {

			@Override
			public void onFocusChange(View v, boolean hasFocus) {

				if (!hasFocus)
					return;

				Calendar now = Calendar.getInstance();
				int year = now.get(Calendar.YEAR);
				int month = now.get(Calendar.MONTH);
				int day = now.get(Calendar.DAY_OF_MONTH);

				ModificaPieActivity context = ModificaPieActivity.this;
				DatePickerDialog datePicker = new DatePickerDialog(context,
						new OnDateSetListener() {
							@Override
							public void onDateSet(DatePicker view, int year,
									int monthOfYear, int dayOfMonth) {
								Intervallo interval = new Intervallo();
								Calendar newDate = Calendar.getInstance();
								newDate.set(Calendar.YEAR, year);
								newDate.set(Calendar.MONTH, monthOfYear);
								newDate.set(Calendar.DAY_OF_MONTH, dayOfMonth);
								interval.setStart(newDate.getTime());
								String editedDate = interval.printStartDate();
								EditText campoData = (EditText) findViewById(R.id.data);
								campoData.setText(editedDate);
								Log.d(toString(), "onDateSet " + editedDate);
							}
						}, year, month, day);
				datePicker.setTitle("Seleziona data");
				datePicker.show();

			}
		});
	}

	// declarative call
	public void annulla(View view) {
		onBackPressed();

	}

	// declarative call
	public void modifica(View view) {
		String testo = extract(R.id.testo);
		String oggetto = extract(R.id.oggetto);
		String date = extract(R.id.data);

		// aggiorno istanza
		pie.setOggetto(oggetto);
		pie.setTesto(testo);
		pie.setData(date);

		// aggiorno db oppure web
		if (isRemote())
			service.saveAsyncTimepie(pie);
		else
			service.update(testo, oggetto, date, pie.getId());

		alert("Evento modificato!");
		onBackPressed();

	}

	// declarative call
	public void crea(View view) {

		String testo = extract(R.id.testo);
		String oggetto = extract(R.id.oggetto);
		String date = extract(R.id.data);

		if ((date.length() == 0) || (testo.length() == 0)) {
			alert("Devono essere compilati almeno i primi due campi!");
			return;
		}

		// aggiorno istanza
		pie = new Timepie(0L, date, oggetto, testo);
		pie.setOwner(service.myPhoneNumber());

		// aggiorno db oppure web
		if (isRemote()) {
			service.saveAsyncTimepie(pie);
			alert("Evento pubblico creato! lo troverai fra gli eventi condivisi.");
		} else {
			service.save(testo, oggetto, date);
			alert("Evento creato!");
		}

		onBackPressed();

	}

	@Override
	public void onBackPressed() {
		Intent intent = new Intent(ModificaPieActivity.this, caller);
		intent.putExtra("pieObj", pie);
		startActivity(intent);
		finish();
	}

	public boolean isRemote() {
		return ((CheckBox) findViewById(R.id.remote)).isChecked();
	}

	private void alert(String text) {
		Toast.makeText(this, text, Toast.LENGTH_LONG).show();
	}

	private String extract(int id) {
		return ((EditText) findViewById(id)).getText().toString();
	}

}